from rest_framework.views import APIView,Response
from goods.models import *
from utils.jwt_tool import JwtTool
from utils.redis import RedisTool


class AddShopping(APIView):
    def post(self, request):
        username = request.data.get("username")
        good_id = request.data.get("good_id")
        # 生成cart_key
        try:
            user = User.objects.get(username=username)
            cart_key = "cart_%s" % user.id
        except Exception as e:
            return Response({"code": 204, "msg": "用户不存在!"})

        # 查商品
        try:
            vege = Vegetable.objects.get(id=good_id)
        except Exception as e:
            return Response({"code": 204, "msg": "当前商品不存在！"})

        redis_conn = RedisTool()

        # 判断历史购物车是否有该商品,列表生成式
        history_goods = [int(i.decode()) for i in redis_conn.redis.hgetall(cart_key).keys()]
        # 判断当前good_id 在不在 history_goods ?
        good_id = int(good_id)
        # good_id在历史购物车
        if good_id in history_goods:
            count = int(redis_conn.redis.hget(cart_key, good_id).decode())
            print(type(count))
            count += 1
            # 判断count是否超出库存
            if count > vege.count:
                return Response({"code": 202, "msg": "商品数量达到限购数量"})
            # 没超出库存，就存入redis
            redis_conn.redis.hset(cart_key, good_id, count)
            return Response({"code": 200, "msg": "新加入购物车成功", "shoppingData": {
                "id": cart_key,  # 购物车id
                "vege_id": good_id,  # 商品id
                "v_name": vege.v_name,  # 商品名称
                "price": vege.price,  # 商品图片
                "veg_text": vege.veg_text,  # 商品价格
                "num": vege.count,  # 商品数量
            }})
        else:
            # 新加入购物车
            count = 1
            if count == vege.count:
                return Response({"code": 202, "msg": "商品数量达到限购数量"})

            # 没超出库存，就存入redis
            redis_conn.redis.hset(cart_key, good_id, count)
            return Response({"code": 200, "msg": "新加入购物车成功", "shoppingData": {
                "id": cart_key,  # 购物车id
                "vege_id": good_id,  # 商品id
                "v_name": vege.v_name,  # 商品名称
                "price": vege.price,  # 商品图片
                "veg_text": vege.veg_text,  # 商品价格
                "num": vege.count,  # 商品数量
            }})


# 删除购物车里的商品
class DelShopping(APIView):
    def delete(self, request):
        gid=request.data.get('good_id')
        username = request.data.get('user')
        user = User.objects.get(username=username)
        cart_key = "cart_%s" % user.id
        # 登录，查询用户在redis中储存的商品信息
        redis_conn = RedisTool()
        redis_conn.redis.hdel(cart_key ,gid)
        return Response({'msg':'删除购物车成功','code':200})